
// ----------------------------------------------------------------------
// <summary>
// 扩展String类，添加Format静态方法，模仿C#中的String.Format方法
// </summary>
// <returns>str</returns>
// ----------------------------------------------------------------------
if (!String.format) {
    String.format = function () {
        if (arguments.length == 0) {
            return null;
        }
        var str = arguments[0];
        if (arguments[1] instanceof Array) {
            var arr = arguments[1];
            for (var i = 0; i < arr.length; i++) {
                var re = new RegExp('\\{' + i + '\\}', 'gm');
                str = str.replace(re, arr[i]);
            }
        } else {
            for (var i = 1; i < arguments.length; i++) {
                var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
                str = str.replace(re, arguments[i]);

            }
        }
        return str;
    }
}

/**
 *js中更改日期
 * y年， m月， d日， h小时， n分钟，s秒
 */
Date.prototype.add = function (part, value) {
    value *= 1;
    if (isNaN(value)) {
        value = 0;
    }
    switch (part) {
        case "y":
            this.setFullYear(this.getFullYear() + value);
            break;
        case "m":
            this.setMonth(this.getMonth() + value);
            break;
        case "d":
            this.setDate(this.getDate() + value);
            break;
        case "h":
            this.setHours(this.getHours() + value);
            break;
        case "n":
            this.setMinutes(this.getMinutes() + value);
            break;
        case "s":
            this.setSeconds(this.getSeconds() + value);
            break;
        default:

    }
    return this;
};
/**
 * 日期格式化方法
 *  var d=new Date();
 console.log(d.toString());    //2011-12-29 11:29:43
 console.log(d.toString(""));    //2011-12-29 11:29:43
 console.log(d.toString("yyyy-MM-dd"));    //2011-12-29
 onsole.log(d.toString("yyyy-MM"));    //2011-12
 onsole.log(d.toString("yyyy/MM"));    //2011/12
 console.log(d.toString("HH:mm:ss"));    //11:29:43
 console.log(d.toString("yyyy-MM-dd HH:mm:ss"));    //2011-12-29 11:29:43
 console.log(d.toString("yyyy年MM月dd日 HH:mm:ss"));    //2011年12月29日 11:29:43
 console.log(d.toString("yyyy-MM-dd HH:mm:ss fff"));    //2011-12-29 11:29:43 862
 * @param format
 * @param loc
 * @return
 */
Date.prototype.toString=function(format,loc){
    var time={};
    time.Year=this.getFullYear();
    time.TYear=(""+time.Year).substr(2);
    time.Month=this.getMonth()+1;
    time.TMonth=time.Month<10?"0"+time.Month:time.Month;
    time.Day=this.getDate();
    time.TDay=time.Day<10?"0"+time.Day:time.Day;
    time.Hour=this.getHours();
    time.THour=time.Hour<10?"0"+time.Hour:time.Hour;
    time.hour=time.Hour<13?time.Hour:time.Hour-12;
    time.Thour=time.hour<10?"0"+time.hour:time.hour;
    time.Minute=this.getMinutes();
    time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;
    time.Second=this.getSeconds();
    time.TSecond=time.Second<10?"0"+time.Second:time.Second;
    time.Millisecond=this.getMilliseconds();
    time.Week=this.getDay();

    var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
    var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"];
    var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];

    var oNumber=time.Millisecond/1000;

    if(format!=undefined && format.replace(/\s/g,"").length>0){
        if(loc!=undefined && loc =="en"){
            MMMArr=MMMArrEn.slice(0);
            WeekArr=WeekArrEn.slice(0);
        }
        format=format
            .replace(/yyyy/ig,time.Year)
            .replace(/yyy/ig,time.Year)
            .replace(/yy/ig,time.TYear)
            .replace(/y/ig,time.TYear)
            .replace(/MMM/g,MMMArr[time.Month-1])
            .replace(/MM/g,time.TMonth)
            .replace(/M/g,time.Month)
            .replace(/dd/ig,time.TDay)
            .replace(/d/ig,time.Day)
            .replace(/HH/g,time.THour)
            .replace(/H/g,time.Hour)
            .replace(/hh/g,time.Thour)
            .replace(/h/g,time.hour)
            .replace(/mm/g,time.TMinute)
            .replace(/m/g,time.Minute)
            .replace(/ss/ig,time.TSecond)
            .replace(/s/ig,time.Second)
            .replace(/fff/ig,time.Millisecond)
            .replace(/ff/ig,oNumber.toFixed(2)*100)
            .replace(/f/ig,oNumber.toFixed(1)*10)
            .replace(/EEE/g,WeekArr[time.Week]);
    }
    else{
        format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;
    }
    return format;
};

/**
 * 根据参数名获取URL中的参数值
 * @param paramName
 * @return 参数值
 */
function getParameter(paramName){
    var query = window.location.search;
    var iLen = paramName.length;
    var iStart = query.indexOf(paramName);
    if (iStart == -1)
        return "";
    iStart += iLen + 1;
    var iEnd = query.indexOf("&", iStart);
    if (iEnd == -1)
        return query.substring(iStart);
    return query.substring(iStart, iEnd);
}

/**
 * 根据参数名获取URL中的参数值
 * @param paramName
 * @return 参数值
 */
function getQueryString(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null){
        return unescape(r[2]);
    }else{
        return null;
    }
}

/**
 * 复制select控件option项到另一个select控件
 */
function selectOptionCopy(sourceCtlId,targetCtlId){
    $("#"+targetCtlId).empty();
    $("#"+sourceCtlId+" option").each(function () {
        var oValue = $(this).val().toString();
        var oText = $(this).text().toString();
        var option = $("<option>").val(oValue).text(oText);
        $("#"+targetCtlId).append(option);
    });
}

/**
 * 根据请求地址动态获取下拉框元素
 * @param selectEleId 下拉框元素ID
 * @param reqUrl ajax请求地址
 * @param textfield 下拉框文本显示字段名
 * @param valuefiled 下拉框选中的值对应的字段名
 * @param defaultSelectedByValue 默认选中项
 * @param endFn 加载完成后执行的函数
 */
function loadSelectOption(selectEleId,reqUrl,textfield,valuefiled,defaultSelectedByValue,endFn){
    if(reqUrl.length == 0) throw "request is required";
    var control = $('#' + selectEleId);
    control.find("option").remove();
    $.ajax({
        url: reqUrl,
        success: function(json){
            if(json){
                var selectVals=new Array();
                $.each(json,function(n,obj){
                    var option = new Option(eval("obj."+textfield),eval("obj."+valuefiled));
                    if(eval("obj.isSelected")==1)option.disabled=true;
                    control[0].options.add(option);
                    if(eval("obj.isDisabled")==1)selectVals.push(eval("obj."+valuefiled));
                });
                if(defaultSelectedByValue!=undefined){
                    //根据value设置默认选中项
                    control.val(defaultSelectedByValue);
                }
                if(endFn != undefined){
                    endFn(json);
                }
                if(selectVals !=undefined && !selectVals && selectVals.length>0)control.val(selectVals);
            }else{
                endFn();
            }
        }
    });
}
/**
 * select2异步搜索
 * @param selectEleId 下拉框元素ID
 * @param reqUrl ajax请求地址
 * @param textfield 下拉框文本显示字段名
 * @param valuefiled 下拉框选中的值对应的字段名
 * @param defaultSelectedByValue 默认选中项
 * @param defaultSearch 默认搜索关键字，搜索框为空时使用
 * @param searchData 查询参数，可以是方法,如果是方法，方法参数是搜索框中的值
 */
function select2Async(selectEleId,reqUrl,textfield,valuefiled,searchData,defaultSelectedByValue,defaultSearch){
    var $select = $("#"+selectEleId);
    $select.select2({
        ajax:{
            url:reqUrl,
            type:"post",
            dataType:"json",
            delay: 600,//输入时延迟查询，单位毫秒
            error:function(){//用户输入会中断请求，导致全局error弹窗
                return false;
            },
            data:function(req){//请求参数 req 为搜索框对象
                var term =  req.term ? req.term.trim():'';
                var data;
                if($.isFunction(searchData)){
                    data = searchData(term) || {};
                }else{
                    data = searchData || {};
                }
                if(term==''){
                    data[valuefiled] = defaultSelectedByValue || '';
                    term = defaultSearch || '';
                }
                data[textfield] = term;
                return data;
            },
            processResults:function(res,req){//显示结果，res 响应结果，req 请求参数（搜索框内容对象，req.term为搜索框的值）
                var option = [];
                option.push({id:"",text:"请选择"});
                for(var i = 0;i<res.length;i++){
                    var op = {};
                    op.id=res[i][valuefiled];
                    op.text=res[i][textfield];
                    option.push(op)
                }
                return {results:option};//result的格式必须是[{id:'',text:''},{id:'',text:''}]
            }
        }
    });
}

/**
 * 根据selectEleId联动选择cascadingSelectEleId下拉框
 * @param selectEleId
 * @param cascadingSelectEleId
 * @param reqUrl
 * @param textfield
 * @param valuefiled
 * @param parameter
 * @param endFn
 */
function cascadingSelect(selectEleId,cascadingSelectEleId,reqUrl,textfield,valuefiled,parameter,endFn){
    $("#"+cascadingSelectEleId).select2();
    $("#"+cascadingSelectEleId).empty();
    $("#"+selectEleId).CascadingSelect(
        $("#"+cascadingSelectEleId),
        reqUrl,
        {
            datatype: "json",
            textfield: textfield,
            valuefiled: valuefiled,
            parameter: parameter
        },
        endFn
    );
}


/**
 * 获取下拉框选中的data属性值
 * 返回对象
 * */
function getSelectData(selectEleId){
    var data = $('#' + selectEleId).find("option:selected").attr("data");
    return data?JSON.parse(data):"";
}

/**
 * 以指定的Json数据，初始化JStree控件
 * JSTree通过JSON数据进行动态绑定，这个JSON的数据格式定义如下
 * {
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}
 *
 * @param treeName 树div名称
 * @param url 数据源地址
 * @param checkbox 是否显示复选框
 * @param loadedfunction 加载完毕的回调函数
 */
function bindJsTree(treeName, url, checkbox, loadedfunction) {
    var control = $('#' + treeName);
    control.data('jstree', false);//清空数据，必须
    var isCheck = arguments[2] || false; //设置checkbox默认值为false
    if(isCheck) {
        //复选框树的初始化
        $.getJSON(url, function (data) {
            control.jstree({
                //'plugins' : [ "checkbox" ], //出现选择框
                //plugins: ["checkbox", "sort", "types", "wholerow", "search", "unique"],
                plugins: ["checkbox", "types", "wholerow", "search", "unique"],//不排序
                'checkbox': { cascade: "", three_state: false }, //不级联
                'core': {
                    'data': data,
                    "themes": {
                        "responsive": false
                    }
                }
            }).bind('loaded.jstree', loadedfunction);
        });
    }
    else {
        //普通树列表的初始化
        $.getJSON(url, function (data) {
            control.jstree({
                'core': {
                    'data': data,
                    "themes": {
                        "responsive": false
                    }
                }
            }).bind('loaded.jstree', loadedfunction);
        });
    }
}

/**
 * 异步加载数据
 * @param treeName
 * @param url
 * @param checkbox 是否显示checkBox，true表示显示，false表示不显示
 * @param isMultiple 是否多选，true表示多选，false表示单选
 * @param loadedfunction
 */
function lazyLoadJsTree(treeName, url, checkbox, isMultiple,loadedfunction) {
    var control = $('#' + treeName);
    control.data('jstree', false);//清空数据，必须
    var isCheck = arguments[2] || false; //设置checkbox默认值为false
    if(isCheck) {
        control.jstree({
            "plugins" : ["checkbox"],
            'checkbox': { cascade: "", three_state: false }, //不级联
            'core' : {
                'multiple': isMultiple,//core中的multiple:false表示单选,true表示多选
                'data': {
                    'url': url, //请求地址
                    'dataType':"json",//返回的数据格式为json
                    'data': function (node) {
                        //返回节点ID表示要进行异步加载
                        return {'id': node.id};
                    }
                }
            }
        }).bind('loaded.jstree', loadedfunction);
    } else {
        control.jstree({
            'core' : {
                'multiple': isMultiple,//core中的multiple:false表示单选,true表示多选
                'data': {
                    'url': url, //请求地址
                    'dataType':"json",//返回的数据格式为json
                    'data': function (node) {
                        return {'id': node.id};
                    }
                }
            }
        }).bind('loaded.jstree', loadedfunction);
    }
}


/**
 * 限制指定输入框元素只能输入非负整数字
 * @param inputElm 输入框元素
 */
function inputInteger(inputElm){
    inputFormat(inputElm,/\D/g,"");
}
/**
 * 输入框格式化，限制输入框不能输入的字符
 * @param inputElm 输入框元素
 * @param reg 需要替换字符串的正则表达式
 * @param toValue 将满足reg正则的字符替换为toValue，缺省值 ''
 */
function inputFormat(inputElm,reg,toValue){
    toValue =  toValue || '';
    var exclusive = [8,35,36,37,38,39,40,48];//排除部分功能跟按键
    var $inputElm =  $(inputElm);
    $inputElm.on("keyup",function(e){
        var oldVal = e.target.value;
        if(oldVal && (exclusive.indexOf(e.keyCode) == -1)) {
            e.target.value=oldVal.replace(reg,toValue)
        }
    });
    $inputElm.on("blur",function(e){
        e.target.value= e.target.value.replace(reg,toValue)
    });
}

/**
 * 限制指定输入框元素只能输入非负数字，保留两位小数
 * @param inputElm 输入框元素
 */
function inputDecimal(inputElm){
    var exclusive = [8,35,36,37,38,39,40,48];//排除部分功能跟按键
    $(inputElm).on("keyup",function(e){
        if(exclusive.indexOf(e.keyCode) == -1) {
            inputDecimalFormat(e.target)
        }
    });
    $(inputElm).on("blur",function(e){
        if(exclusive.indexOf(e.keyCode) == -1) {
            overDecimalFormat(e.target)
        }
    });
}
/**
 * Created by laotou on 2016/11/3.
 */
/**
 * 强制输入框只能输入纯数字
 * 实时动态强制更改用户录入
 * arg1 inputObject
 **/
function inputIntegerFormat(th){
    th.value=th.value.replace(/\D/g,'')
}
/**
 * 强制输入框只能输入正数，最多两位数字
 * 主要用于金额输入
 * 实时动态强制更改用户录入
 * arg1 inputObject
 **/
function inputDecimalFormat(th){
    var regStrs = [
        [/^0(\d+)$/g, '$1'], //禁止录入整数部分两位以上，但首位为0
        [/[^\d\.]+$/g, ''], //禁止录入任何非数字和点
        [/\.(\d?)\.+/g, '.$1'], //禁止录入两个以上的点
        [/^(\d+\.\d{2}).+/g, '$1'], //禁止录入小数点后两位以上
        [/^\./g, ''] //禁止录入第一位是小数点
    ];
    for(var i=0; i<regStrs.length; i++){
        var reg = regStrs[i][0];
        th.value = th.value.replace(reg, regStrs[i][1]);
    }
}
/**
 * 强制输入框只能输入正数，最多两位数字
 *
 * 录入完成后，输入模式失去焦点后对录入进行判断并强制更改，并对小数点进行0补全
 * arg1 inputObject
 *
 **/
function overDecimalFormat(th){
    var v = th.value;
    if(v === ''){
        //v = '0.00';
    }else if(v.match(/^0*$/g)){
        v = '0.00';
    }else if(v === '0.'){
        v = '0.00';
    }else if(/^0+\d+\.?\d*.*$/.test(v)){
        v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');
        //v = inp.getRightPriceFormat(v).val;
    }else if(/^0\.\d$/.test(v)){
        v = v + '0';
    }else if(!/^\d+\.\d{2}$/.test(v)){
        if(/^\d+\.\d{2}.+/.test(v)){
            v = v.replace(/^(\d+\.\d{2}).*$/, '$1');
        }else if(/^\d+$/.test(v)){
            v = v + '.00';
        }else if(/^\d+\.$/.test(v)){
            v = v + '00';
        }else if(/^\d+\.\d$/.test(v)){
            v = v + '0';
        }else if(/^[^\d]+\d+\.?\d*$/.test(v)){
            v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');
        }else if(/\d+/.test(v)){
            v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');
            ty = false;
        }else if(/^0+\d+\.?\d*$/.test(v)){
            v = v.replace(/^0+(\d+\.?\d*)$/, '$1');
            ty = false;
        }else{
            v = '0.00';
        }
    }
    th.value = v;
}

/**
 * 填充Form表单数据
 * @param jsonStr
 * @param formId 要填充的表单id,如果不传 则对body内的所哟出入框填充
 */
function fillForm(jsonStr,formId){
    var obj =jsonStr;
    var key,value,tagName,type,arr;
    var formObj = formId ? $("#"+formId):$("body");
    for(var x in obj){
        key = x;
        value = obj[x];

        formObj.find("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    if($(this).val()==value){
                        $(this).iCheck('check');
                    }else{
                        $(this).iCheck('uncheck');
                    }
                }else if(type=='checkbox'){
                    arr = value.split(',');
                    for(var i =0;i<arr.length;i++){
                        if($(this).val()==arr[i]){
                            $(this).iCheck('check');
                            break;
                        }
                    }
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value).trigger("change");
                //$(this).val(value);
            }

        });
    }
}
/**
 * 根据指定类型标签的指定属性的值与json对象key值对应
 * 填充text
 * @param jsonStr json格式数据
 * @param elmType 标签类型
 * @param attrName 属性名称，缺省值name
 */
function loadText(jsonStr,elmType,attrName){
    var obj =jsonStr;
    if(!attrName) {
        attrName = "name" ;
    }
    for(var x in obj){
        var $elm = $(elmType + "["+attrName+"=" + x + "]");
        if($elm){
            $elm.text(obj[x])
        }
    }
}
function cleanSelect2Span(str){
    $('#select2-'+str+'-container').attr('title','').html('');
}
function cleanCheckedRadio(name){
    $("input[name='"+name+"']").iCheck('uncheck');
}
function checkedRadio(name,value){
    $("input[name='"+name+"'][value='"+value+"']").iCheck('check');
}

function emoji(str){
    return twemoji.parse(str, function(icon, options, variant){
        return g_comm.basePath+'/plugins/twemoji/16x16/'+icon+options.ext;
    });
}
function emoji2(str){
    var str = twemoji.parse(str, function(icon, options, variant){
        return g_comm.basePath+'/plugins/twemoji/16x16/'+icon+options.ext;
    });
    return str.replace(/\\"/g,'');
}
/*function loadSelectOption(selectEleId,reqUrl,textfield,valuefiled,defaultSelectedByValue,endFn){
    var control = $('#' + selectEleId);
    control.find("option").remove();
    control.prepend("<option value=''>请选择</option>");
    control.FillOptions(reqUrl, {
        datatype: "json",
        textfield: textfield,
        valuefiled: valuefiled,
        selectedindex:-1,
        keepold: true,
        callback:function(datas,selectVals){
            if(defaultSelectedByValue!=undefined){
                //根据value设置默认选中项
                control.val(defaultSelectedByValue).trigger("change");
            }
            if(typeof endFn =="function"){
                endFn(datas);
            }
            if(selectVals !=undefined && !selectVals && selectVals.length>0)control.val(selectVals).trigger("change");
        }
    });
}*/
function layerAlert(text){
    layer.alert(text,{
        title: '提示框',
        icon:0
    });
}
function getObjByName(name, type){
    return $(type+"[name='"+name+"']");
}
function getObjValByName(name, type){
    var $obj = getObjByName(name, type);
    var elmType = $obj.attr("type");
    if(elmType == 'radio'){
        return $(type+":checked[name='"+name+"']").val();
    }
    if(elmType == 'checkbox'){
        return $(type+":checked[name='"+name+"']").val();
    }
    return $obj.val();
}
function getObjValById(id){
    return $("#"+id).val();
}

function playAnswer(tableObj){
    tableObj.on("click", "a.fileSee", function () {
        var type = $(this).attr("ttype");
        var url = $(this).attr("turl");
        if(type==1){
            layer.open({
                type: 2,
                title: false,
                area: ['960px', '560px'],
                shade: 0.8,
                closeBtn: 0,
                shadeClose: true,
                content: url
            });
        }else if(type==2){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                area: ['90%', '90%'],
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: '<img class="openImg" src="'+url+'" />'
            });
        }else{
            layer.alert('<video controls="" autoplay="" name="media"><source src="'+url+'" type="video/mp4"></video>',{
                title: '播放语音',
                shade: false,
                btn: ['关闭']
            });
        }
    });
}

//手机号和座机数字正则验证
function isMobile(value){
    var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    var isMob=/^((\+?86)|(\+86))?(13[0123456789][0-9]{8}|15[0123456789][0-9]{8}|18[023456789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    if(isMob.exec(value)||isPhone.exec(value)){
        return true;
    }else{
        return false;
    }
}


/**
 *通过post请求下载（导出）文件，
 * @param url 下载地址
 * @param jsonData 请求参数，任意参数，只要第一级为json形式即可
 * 如 {id:"dd",name:"tom",houseId:["xxx","yyy"],houseUser:{id:"bb",name:"liza"}}
 * 或 {id:"dd",name:"tom",houseId:"xxx,yyy",houseUser:"id=bb&name=lixa"}
 * 等
 * 二级以上参数形式不限，只作为一级参数的value值上传
 * @param afterDownload 导出后进行的自定义操作,在用户点击保存，浏览器弹出保存文件窗口后执行（子窗口的subWindow.onbeforeunload事件）
 * 				不管用户是否保存都会执行。
 */
function postRequestDownload(url,jsonData,afterDownload){
    //创建一个隐藏的form用来提交参数
    var $exportForm = $(String.format("<form id='exportSubmitForm' action='{0}' method='post' target='_self' style='display: none'></form>",url));
    //将所有一级参数添加到隐藏form中，所有二级以上参数作为对应一级参数 的value值
    for (var key in jsonData){
        var hidden = String.format("<input  type='hidden' name='{0}' value='{1}'/>",key,jsonData[key]);
        $exportForm.append(hidden);
    }
    $("body").append($exportForm);
    //绑定提交事件，提交后弹窗下载
    $("#exportSubmitForm").submit(function (){
        //_self 在当前窗口打开 ；_blank 加载到一个新的窗口。这是默认。修改此参数需修改隐藏form中的target属性
        var subWindow = window.open('about:blank',"_self",'height=400, width=400, top=0, left=0, toolbar=yes,depended=no, menubar=yes, scrollbars=yes, resizable=yes,location=yes, status=yes');
        //弹出保存文件窗口后执行的操作，用户自定义
        if($.isFunction(afterDownload)){
            subWindow.onbeforeunload = afterDownload;
        }
    });
    $("#exportSubmitForm").submit().remove();//提交请求，移除隐藏form
}
/**
 * 导出excel
 *  无弹窗、选列
 * @param url 导出地址
 * @param columns 导出的列 格式为json数组，每一项必须包含field（属性）和title(列名):
 *       [{field: 'nickname',title: '昵称'},{field: 'userName',title: '姓名'}]
 * @param jsonData 要传的其它参数 json格式
 * @param afterExport 导出后执行的方法
 */
function exportExcel(url ,columns,jsonData , afterExport) {
    jsonData = jsonData || {};
    jsonData.columns = JSON.stringify(columns);
    postRequestDownload(url,jsonData,afterExport);
}
/**
 * 导出excel弹窗
 *   待优化 弹窗、选列、
 *   UI ? 不存在的
 * @param url
 * @param selectedColumns 已选择的导出列 格式为json数组，每一项必须包含field（属性）和title(列名):
 *       [{field: 'nickname',title: '昵称'},{field: 'userName',title: '姓名'}]
 * @param jsonData
 * @param unSelectedColumns 未选择的导出列 格式为json数组，每一项必须包含field（属性）和title(列名):
 *       [{field: 'nickname',title: '昵称'},{field: 'userName',title: '姓名'}]
 * @param afterExport
 */
function exportExcelLayer(url ,selectedColumns,jsonData ,unSelectedColumns, afterExport) {
    if(!jsonData) jsonData = {};
    var div = '<div class="ibox-content form-horizontal" >' +
                '<div class="modal-body" style="height: 250px">' +
                    '<div class="panel panel-default" style="float: left;">' +
                        '<div class="panel-heading">' +
                            '<h3 class="panel-title">已选导出列</h3>' +
                        '</div>' +
                        '<div class="panel-body">' +
                            '<ul id="sortable" class="connectedSortable list-group" style="min-height: 40px;">' +
                            '</ul>' +
                        '</div>' +
                    '</div>' +
                    '<div class="panel panel-default"  style="float: left;">' +
                        '<div class="panel-heading">' +
                            '<h3 class="panel-title">未选导出列</h3>' +
                        '</div>' +
                        '<div class="panel-body">' +
                            '<ul id="noSortable" class="connectedSortable list-group" style="min-height: 40px;">' +
                            '</ul>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' ;
    layer.open({
        closeBtn:1,
        type: 1,
        title: "导出excel",
        area: ['auto', '80%'], //宽高
        content: div,
        btn:['导出','取消'],
        yes:function(index, layero){
            var columns = [];

            $($("#sortable li input")).each(function (index, obj) {
                var liv = {"field":obj.name,"title":obj.value}
                columns.push(liv);
            });
            if(columns.length == 0){
                layerAlert("请选择至少一个导出列");
                return false;
            }
            exportExcel(url,columns,jsonData,afterExport);
            return true;
        }
    });
    if(selectedColumns) {
        for (var i = 0; i < selectedColumns.length; i++) {
            var liv = selectedColumns[i];
            var li = String.format('<li class="ui-state-default list-group-item" style="list-style-type:none;"><span>&nbsp;</span><input type="hidden" name="{0}" value="{1}"/>{2}</li>', liv.field, liv.title, liv.title);
            $("#sortable").append(li);
        }
    }
    if(unSelectedColumns) {
        for (var i = 0; i < unSelectedColumns.length; i++) {
            var liv = unSelectedColumns[i];
            var li = String.format('<li class="ui-state-highlight list-group-item" style="list-style-type:none;"><span>&nbsp;</span><input type="hidden" name="{0}" value="{1}"/>{2}</li>', liv.field, liv.title, liv.title);
            $("#noSortable").append(li);
        }
    }
    $("#sortable, #noSortable" ).sortable({
        connectWith: ".connectedSortable",
        dropOnEmpty: true,
        placeholder: "ui-state-highlight"
    }).disableSelection();

}

//验证身份证号
function isIdCard(value){
    return idCard(value);
}
var idCard = function (value) {
    if (value.length == 18 && 18 != value.length) return false;
    var number = value.toLowerCase();
    var d, sum = 0, v = '10x98765432', w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], a = '11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91';
    var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/);
    if (re == null || a.indexOf(re[1]) < 0) return false;
    if (re[2].length == 9) {
        number = number.substr(0, 6) + '19' + number.substr(6);
        d = ['19' + re[4], re[5], re[6]].join('-');
    } else d = [re[9], re[10], re[11]].join('-');
    if (!isDateTime.call(d, 'yyyy-MM-dd')) return false;
    for (var i = 0; i < 17; i++) sum += number.charAt(i) * w[i];
    return (re[2].length == 9 || number.charAt(17) == v.charAt(sum % 11));
};
var isDateTime = function (format, reObj) {
    format = format || 'yyyy-MM-dd';
    var input = this, o = {}, d = new Date();
    var f1 = format.split(/[^a-z]+/gi), f2 = input.split(/\D+/g), f3 = format.split(/[a-z]+/gi), f4 = input.split(/\d+/g);
    var len = f1.length, len1 = f3.length;
    if (len != f2.length || len1 != f4.length) return false;
    for (var i = 0; i < len1; i++) if (f3[i] != f4[i]) return false;
    for (var i = 0; i < len; i++) o[f1[i]] = f2[i];
    o.yyyy = s(o.yyyy, o.yy, d.getFullYear(), 9999, 4);
    o.MM = s(o.MM, o.M, d.getMonth() + 1, 12);
    o.dd = s(o.dd, o.d, d.getDate(), 31);
    o.hh = s(o.hh, o.h, d.getHours(), 24);
    o.mm = s(o.mm, o.m, d.getMinutes());
    o.ss = s(o.ss, o.s, d.getSeconds());
    o.ms = s(o.ms, o.ms, d.getMilliseconds(), 999, 3);
    if (o.yyyy + o.MM + o.dd + o.hh + o.mm + o.ss + o.ms < 0) return false;
    if (o.yyyy < 100) o.yyyy += (o.yyyy > 30 ? 1900 : 2000);
    d = new Date(o.yyyy, o.MM - 1, o.dd, o.hh, o.mm, o.ss, o.ms);
    var reVal = d.getFullYear() == o.yyyy && d.getMonth() + 1 == o.MM && d.getDate() == o.dd && d.getHours() == o.hh && d.getMinutes() == o.mm && d.getSeconds() == o.ss && d.getMilliseconds() == o.ms;
    return reVal && reObj ? d : reVal;
    function s(s1, s2, s3, s4, s5) {
        s4 = s4 || 60, s5 = s5 || 2;
        var reVal = s3;
        if (s1 != undefined && s1 != '' || !isNaN(s1)) reVal = s1 * 1;
        if (s2 != undefined && s2 != '' && !isNaN(s2)) reVal = s2 * 1;
        return (reVal == s1 && s1.length != s5 || reVal > s4) ? -10000 : reVal;
    }
};

//判断用户输入的电子邮箱格式是否正确
function checkEmail(email){
    var isEmail=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;

    if(isEmail.test(email)){
        return true;
    }else{
        return false;
    }
}

/**
 * 同步加载数据
 * @param url
 */
function loadDetailData(url,param){
    var detail;
    $.ajax({
        async:false,
        data:param,
        type:"post",
        url:url,
        success:function(result){

            if(result.code == 0){
                detail =  result.data;
            }else{
                detail = {};
                layerAlert(result.msg);
            }
        }
    });
    return detail;
}

/*
 参数解释：
 title	标题
 contentDivId		内容DIV的ID
 w		            弹出层宽度（缺省调默认值）
 h		            弹出层高度（缺省调默认值）
 */
function showLayerDialog(title,contentDivId,w,h,callbackFunction){
    if (title == null || title == '') {
        title=false;
    }
    if (w == null || w == '') {
        w=800+'px';
    }
    if (h == null || h == '') {
        h=($(window).height() - 50)+'px';
    }
    if(callbackFunction!=undefined){
        layer.open({
            type: 1,//页面层
            maxmin: true,
            area: [w, h],
            scrollbar: false, // 父页面 滚动条 禁止
            title: title,
            content: $("#"+contentDivId),
            success: function(layero, index){
                callbackFunction(layero,index);
            }
        });
    }else {
        layer.open({
            type: 1,//页面层
            maxmin: true,
            area: [w, h],
            scrollbar: false, // 父页面 滚动条 禁止
            title: title,
            content: $("#"+contentDivId)
        });
    }

}

/*
 参数解释：
 title	标题
 url		请求的url
 id		需要操作的数据id
 w		弹出层宽度（缺省调默认值）
 h		弹出层高度（缺省调默认值）
 */
function showLayerPage(title,url,w,h){
    if (title == null || title == '') {
        title=false;
    }
    if (w == null || w == '') {
        w=800+"px";
    }
    if (h == null || h == '') {
        h=($(window).height() - 50)+"px";
    }
    layer.open({
        type: 2,
        area: [w, h],
        fix: false, //不固定
        maxmin: true,
        scrollbar: false,//屏蔽游览器滚动条
        shade:0.4,
        title: title,
        content: url
    });
}